package cn.hacz.edu.fastjson;

import cn.hacz.edu.entity.PersonEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * project -
 * description -
 *
 * @author：guod <br/>
 * ===============================
 * Created with IDEA
 * Date：2018/2/8
 * Time：15:43
 * JDK: 1.8
 * Version:1.0
 * ================================
 */
public class FastJson01MainTest {
    PersonEntity person01 = new PersonEntity("guod", 22, "18838177689");
    PersonEntity person02 = new PersonEntity("guod", 22, "18838177689");

    @Test
    public void fastJson01MainTest01() {
        // 序列化
        String s = JSON.toJSONString(person01);
        System.out.println(s);
        // 反序列化（两种方式）
        JSONObject jsonObject = JSON.parseObject(s);
        PersonEntity personEntity = JSON.parseObject(s, PersonEntity.class);
        System.out.println(jsonObject);
        System.out.println(personEntity);
    }

    @Test
    public void fastJson01MainTest02() {
        List<PersonEntity> personEntities = new ArrayList<>();
        personEntities.add(person01);
        personEntities.add(person02);
        // 序列化
        String s = JSON.toJSONString(personEntities);
        System.out.println(s);

        // 反序列化
        JSONArray jsonArray = JSON.parseArray(s);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            System.out.println(name);
        }

        // 反序列化
        List<PersonEntity> personEntities1 = JSON.parseArray(s, PersonEntity.class);
        for (int i = 0; i < personEntities1.size(); i++) {
            PersonEntity personEntity = personEntities1.get(i);
            System.out.println(personEntity.getAge());
        }
    }
}
